﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using RebEngine.Managers;

namespace RebEngine.GameComponents
{
    public class Timer
    {
        static List<Timer> Timers = new List<Timer>();

        private double dTimeRemaining;
        private double dInterval;

        private bool bContinousTimer;

        public delegate void Fire ();
        public event Fire TimerFinished;

        public void Start(double interval, bool continuous)
        {
            Timers.Remove(this);
            Timers.Add(this);
            this.dInterval = interval;
            this.dTimeRemaining = interval;
            bContinousTimer = continuous;
            LogManager.Write("Timer: Created for " + dInterval.ToString() + " seconds");
        }
          
        public void Stop()
        {
            Timers.Remove(this);
        }

        public static void Update(GameTime gameTime)
        {
            for (int i = Timers.Count - 1; i >= 0; i--)
            {
                

                Timers[i].dTimeRemaining -= gameTime.ElapsedGameTime.TotalSeconds;
                if (Timers[i].dTimeRemaining <= 0)
                {
                    if(Timers[i].TimerFinished != null)
                        Timers[i].TimerFinished();

                    LogManager.Write("Timer finished");
                    if (Timers[i].bContinousTimer == true)
                        Timers[i].dTimeRemaining = Timers[i].dInterval;
                    else
                        Timers[i].Stop();
                }
            }
        }

        public void ChangeInterval(int seconds)
        {
            dInterval = seconds;
        }

    }
}
